(function () {
    "use strict";
    const deleteAll = document.querySelector('.deleteAll'),
        selectBox = document.querySelector('.selectBox'),
        searchInp = document.querySelector('.searchInp'),
        tableBox = document.querySelector('.tableBox'),
        tbody = tableBox.querySelector('tbody'),
        checkAll = document.querySelector('#checkAll');
    let checkboxList = [];

    // 部门列表的绑定
    const bindDepartment = async () => {
        let departList = await api.queryDepartmentList();
        let frag = document.createDocumentFragment();
        departList.forEach(item => {
            let option = document.createElement('option');
            option.value = item.id;
            option.innerHTML = item.name;
            frag.appendChild(option);
        });
        selectBox.appendChild(frag);
        frag = null;
    };
    bindDepartment();

    // 获取员工信息 & 绑定在表格中
    const init = async () => {
        // 获取数据
        let departmentId = selectBox.value,
            search = searchInp.value.trim(),
            userList = [];
        try {
            let { code, data } = await http.get('/user/list', {
                params: {
                    departmentId,
                    search
                }
            });
            if (+code === 0) userList = data;
        } catch (_) { }

        // 绑定数据
        let str = ``;
        userList.forEach(item => {
            let { id, name, sex, email, phone, department, job, desc } = item;
            str += `<tr style="background:${+id === 1 ? '#DDD' : ''}">
                <td class="w3">
                    ${+id === 1 ?
                    `` :
                    `<input type="checkbox" name="checkbox" value="${id}"/>`}
                </td>
                <td class="w10">${name}</td>
                <td class="w5">${+sex === 0 ? '男' : '女'}</td>
                <td class="w10">${department}</td>
                <td class="w10">${job}</td>
                <td class="w15">${email}</td>
                <td class="w15">${phone}</td>
                <td class="w20">${desc}</td>
                <td class="w12" myId="${id}">
                    ${+id === 1 ?
                    `` :
                    `
                    <a href="useradd.html?userId=${id}">编辑</a>
                    <a href="javascript:;">删除</a>
                    <a href="javascript:;">重置密码</a>
                    `}
                </td>
            </tr>`;
        });
        tbody.innerHTML = str;

        // 获取所有复选框
        handleCheck();
    };
    init();

    // 搜索操作
    selectBox.onchange = init;
    searchInp.oninput = utils.throttle(init);

    // 重置密码 & 单一删除
    tbody.onclick = async function (ev) {
        let target = ev.target,
            text = '',
            userId;
        if (target.tagName !== 'A') return;
        userId = target.parentNode && target.parentNode.getAttribute('myId');
        text = target.innerHTML;
        if (text === '重置密码') {
            let flag = confirm('您确定要重置此用户的密码吗?');
            if (!flag) return;
            let { code } = await http.post('/user/resetpassword', {
                userId,
                password: md5('1234567890')
            });
            if (+code === 1) {
                alert('当前操作失败，请稍后再试');
                return;
            }
            alert('恭喜您，当前操作成功');
            return;
        }

        if (text === '删除') {
            let flag = confirm('您确定要删除此用户吗？');
            if (!flag) return;
            let { code } = await http.get('/user/delete', {
                params: {
                    userId
                }
            });
            if (+code !== 0) {
                alert('删除失败，请稍后再试~');
                return;
            }
            // 移除删除的内容：移除DOM「推荐」 或者 重新从服务器获取列表数据
            tbody.removeChild(target.parentNode.parentNode);
            handleCheck();
            alert('恭喜您，删除成功~');
        }
    };

    // 全选/全不选 & 批量删除
    const handleCheck = () => {
        checkboxList = Array.from(document.getElementsByName('checkbox'));
        checkboxList.forEach(item => {
            item.onchange = function () {
                let flag = true;
                checkboxList.forEach(item => {
                    if (!item.checked) flag = false;
                });
                checkAll.checked = flag;
            };
        });
    };
    checkAll.onchange = function () {
        checkboxList.forEach(item => {
            item.checked = checkAll.checked;
        });
    };
    deleteAll.onclick = function () {
        let flag = confirm('您确定要批量删除吗？');
        if (!flag) return;

        let ids = [];
        checkboxList.forEach(item => {
            if (item.checked) {
                ids.push(item.value);
            }
        });
        if (ids.length === 0) {
            alert('请至少选择一项!');
            return;
        }

        let n = 0;
        const next = async userId => {
            if (n > ids.length) {
                alert('恭喜您，操作成功~，请稍后再试~');
                init();
                return;
            }
            try {
                let { code } = await http.get('/user/delete', {
                    params: {
                        userId
                    }
                });
                if (+code === 0) {
                    next(ids[n++]);
                    return;
                }
            } catch (_) { }
            alert('删除失败~，请稍后后再试~');
            init();
        };
        next(ids[n++]);
    };



})();